package org.fqh.system.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.fqh.common.base.Constants;
import org.fqh.system.entity.TSysUser;
import org.fqh.system.service.TSysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
* @author fqh 
* @version 创建时间：2017年11月29日 下午3:13:17
* 类说明
*/
@Controller
@RequestMapping("/sysuser")
public class TSysUserController {
	
	@Autowired 
	TSysUserService userService;
	
	@RequestMapping("/list")
	public String list(Model model,@RequestParam(required=false,defaultValue="1")int pageNO) {
	    int size=Constants.PAGE_SIZE; 
		PageHelper.startPage(pageNO, size);
	    List<TSysUser> user =new ArrayList<>();
		try {
			user = userService.selectAll();
		    model.addAttribute("user", user);
		    PageInfo<TSysUser> page = new PageInfo<TSysUser>(user);
		    model.addAttribute("page", page);
		    return "system/sysuser/userList";
		} catch (Exception e) {
			e.printStackTrace();
			return "500";
		}
	 
		
	}
    @RequestMapping("/add")
	public String add(Model model,String pid,String sort) {
    	model.addAttribute("pid",pid);
    	model.addAttribute("sort",sort);	
		return "system/sysuser/userAdd";
	}
    @RequestMapping("/save")
    @ResponseBody
	public String save(Model model,TSysUser user) {
    	String result = new String();
    	if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())||StringUtils.isEmpty(user.getPassword())) {
    		result="用户名或密码为空";
    	}
    	else {
    		try {
    			userService.insert(user);
    			result = "success";
    		}catch(Exception e){
    			e.printStackTrace();
    			result = "系统错误";
    		}
    	}
		
	    return result;
	}
    
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String id) {
    	String result = new String();
    	try {
    		userService.delete(Integer.parseInt(id));
    		result = "success";
    	}catch(Exception e) {
    		e.printStackTrace();
    		result = "fail";
    	}
    	
		return result;	
    }
    @RequestMapping("/get/{id}")
    @ResponseBody
    public String getUserById(@PathVariable("id")int id) {
    	
    	String result = new String();
    	try {
    		TSysUser  user = userService.GetById(id);
    		result = JSON.toJSONString(user );
    	}catch(Exception e) {
    		e.printStackTrace();
    	 
    	}
    	return result;
    }
  
}
